package com.zhaojonhy.zhaopangwb.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.CommentsAPI;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.StatusCommentAdapter;
import com.zhaojonhy.zhaopangwb.adapter.StatusGridImgsAdapter;
import com.zhaojonhy.zhaopangwb.bean.Comment;
import com.zhaojonhy.zhaopangwb.bean.CommentsShow;
import com.zhaojonhy.zhaopangwb.bean.PicUrls;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.utils.DateUtils;
import com.zhaojonhy.zhaopangwb.utils.ImageOptHelper;
import com.zhaojonhy.zhaopangwb.utils.StringUtils;
import com.zhaojonhy.zhaopangwb.utils.TitleBuilder;
import com.zhaojonhy.zhaopangwb.widget.WrapHeightGridView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/22.
 */

public class StatusDetailActivity extends Activity implements
        OnClickListener , RadioGroup.OnCheckedChangeListener {

    private static final String TAG = StatusDetailActivity.class.getSimpleName() ;

    //跳转到评论页面
    private static final int REQUEST_CODE_WRITE_COMMENT = 2333;

    //listView headView 微博信息，包括头像，微博名等
    private View status_detail_info; //view布局
    private ImageView iv_avatar; //头像
    private TextView tv_subhead; //标题-微博名
    private TextView tv_caption; //说明
    //微博正文及图片，单图或者多图
    private FrameLayout include_status_image; //二者选其一
    private WrapHeightGridView gv_img; //多图
    private ImageView iv_img; //单图
    private TextView tv_content; // 微博正文
    //微博引用正文及图片，单图或者多图
    private View include_status_retweeted;
    private FrameLayout include_status_retweeted_image; //二者选其一
    private WrapHeightGridView gv_retweeted_img; //多图
    private ImageView iv_retweeted_img; //单图
    private TextView tv_retweeted_content; // 微博正文
    //shadow_tab 顶部悬浮的菜单栏
    private View shadow_status_detail_tab;
    //转发，评论，赞
    private RadioGroup shadow_rg_status_detail;
    private RadioButton shadow_rb_retweets;
    private RadioButton shadow_rb_comments;
    private RadioButton shadow_rb_likes;
    //listView headView 顶部菜单栏,添加到列表中作为header的菜单栏
    private View status_detail_tab;
    //转发，评论，赞
    private RadioGroup rg_status_detail;
    private RadioButton rb_retweets;
    private RadioButton rb_comments;
    private RadioButton rb_likes;
    //listView 下拉刷新控件
    private PullToRefreshListView plv_status_detail;
    //footView 加载更多
    private View footView;
    //底部的互动栏包括，转发、评论、点赞
    private LinearLayout ll_bottom_control;
    private LinearLayout ll_share_bottom;
    private TextView tv_share_bottom;
    private LinearLayout ll_comment_bottom;
    private TextView tv_comment_bottom;
    private LinearLayout ll_like_bottom;
    private TextView tv_like_bottom;

    /**
     * 当前 Token 信息
     */
    private Oauth2AccessToken mAccessToken;
    private CommentsAPI mCommentsAPI;//微博评论的API
    //详情页的微博信息
    private Statuses statuses ;
    // 是否需要滚动至评论部分
    private boolean scroll2Comment;
    // 评论当前已加载至的页数
    private int curPage = 1;

    private List<Comment> comments = new ArrayList<Comment>();
    private StatusCommentAdapter adapter ;

    protected ImageLoader imageLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_status_details);

        imageLoader = ImageLoader.getInstance() ;

        // 获取intent传入的信息
        statuses = (Statuses) getIntent().getSerializableExtra("status") ;
        scroll2Comment = getIntent().getBooleanExtra("scroll2Comment" ,false ) ;

        // 初始化View
        initView();

        // 设置数据信息
        setData();

        // 开始加载第一页评论数据
        addFootView(plv_status_detail, footView);
        loadComments(1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titleBarIvLeft:
                StatusDetailActivity.this.finish();
                break;
            case R.id.ll_share_bottom:
                Intent intentWriteStatus = new Intent(this, WriteStatusActivity.class);
                intentWriteStatus.putExtra("status", statuses);
                intentWriteStatus.putExtra("isRetweet",true ) ;
                startActivity(intentWriteStatus);
                break;
            case R.id.ll_comment_bottom:
                //跳转至评论页面
                Intent intent = new Intent(this, WriteCommentAcyivity.class);
                intent.putExtra("status", statuses);
                startActivityForResult(intent ,REQUEST_CODE_WRITE_COMMENT); // 做一个反馈,标识作用
                break;
            case R.id.ll_like_bottom:
                break;
            case R.id.gv_images:
                break;
            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        // 更新tab菜单栏某个选项时,注意header的菜单栏和shadow菜单栏的选中状态同步
        switch (checkedId) {
            case R.id.rb_retweets:
                shadow_rb_retweets.setChecked(true);
                rb_retweets.setChecked(true);
                break;
            case R.id.rb_comments:
                shadow_rb_comments.setChecked(true);
                rb_comments.setChecked(true);
                break;
            case R.id.rb_likes:
                shadow_rb_likes.setChecked(true);
                rb_likes.setChecked(true);
                break;
            default:
                break;
        }
    }

    private void initView() {
        //title 标题栏
        initTitle();
        //listView headView 微博信息
        initDetailHead();
        //tab 菜单栏
        initTab();
        //listView 下拉刷新控件
        initListView();
        //bottom control 底部互动栏
        initBottomBar();
    }

    private void initTitle() {

        new TitleBuilder(this)
                .setTitleText("微博正文")
                .setLeftImage(R.drawable.navigationbar_back_sel)
                .setLeftOnClickListener(this);

    }

    private void initDetailHead() {
        status_detail_info = View.inflate(this, R.layout.items_status, null);
        status_detail_info.setBackgroundResource(R.color.white);
        //不要原先的底部操作栏(底部单独添加操作栏)
        status_detail_info.findViewById(R.id.include_bottom_control).setVisibility(View.GONE);

        iv_avatar = (ImageView) status_detail_info.findViewById(R.id.iv_avatar);
        tv_subhead = (TextView) status_detail_info.findViewById(R.id.tv_subhead);
        tv_caption = (TextView) status_detail_info.findViewById(R.id.tv_caption);

        include_status_image = (FrameLayout) status_detail_info.findViewById(R.id.include_status_image);
        gv_img = (WrapHeightGridView) include_status_image.findViewById(R.id.gv_images);
        iv_img = (ImageView) include_status_image.findViewById(R.id.iv_image);
        tv_content = (TextView) status_detail_info.findViewById(R.id.tv_content);

        include_status_retweeted = status_detail_info.findViewById(R.id.include_retweeted_status);
        tv_retweeted_content = (TextView) include_status_retweeted.findViewById(R.id.tv_resweeted_content);
        include_status_retweeted_image = (FrameLayout) include_status_retweeted.
                findViewById(R.id.include_retweeted_status_image);

        gv_retweeted_img = (WrapHeightGridView) include_status_retweeted_image.findViewById(R.id.gv_images);
        iv_retweeted_img = (ImageView) include_status_retweeted_image.findViewById(R.id.iv_image);

        iv_img.setOnClickListener(this);
    }

    private void initTab() {
        //shadow_tab 顶部悬浮的菜单栏
        shadow_status_detail_tab = findViewById(R.id.status_detail_tab);
        shadow_rg_status_detail = (RadioGroup) shadow_status_detail_tab
                .findViewById(R.id.rg_status_detail);
        //转发，评论，赞
        shadow_rb_retweets = (RadioButton) shadow_status_detail_tab.findViewById(R.id.rb_retweets);
        shadow_rb_comments = (RadioButton) shadow_status_detail_tab.findViewById(R.id.rb_comments);
        shadow_rb_likes = (RadioButton) shadow_status_detail_tab.findViewById(R.id.rb_likes);
        shadow_rg_status_detail.setOnCheckedChangeListener(this);

        //listView headView 顶部菜单栏,添加到列表中作为header的菜单栏
        status_detail_tab = View.inflate(this, R.layout.status_detail_tab, null);
        rg_status_detail = (RadioGroup) status_detail_tab
                .findViewById(R.id.rg_status_detail);
        //转发，评论，赞
        rb_retweets = (RadioButton) status_detail_tab.findViewById(R.id.rb_retweets);
        rb_comments = (RadioButton) status_detail_tab.findViewById(R.id.rb_comments);
        rb_likes = (RadioButton) status_detail_tab.findViewById(R.id.rb_likes);
        rg_status_detail.setOnCheckedChangeListener(this);
    }

    //通过listView的addHeadView 做微博下拉刷新
    private void initListView() {
        //listView 下拉刷新控件
        plv_status_detail = (PullToRefreshListView) findViewById(R.id.plv_status_detail);
        //微博信息的adapter
        adapter = new StatusCommentAdapter(this, comments) ;
        plv_status_detail.setAdapter(adapter); //先设置一个空的adapter 后面更新

        //加载更多
        footView = View.inflate( this,R.layout.footview_loading,null ) ;
        ListView lv = plv_status_detail.getRefreshableView() ; //我们需要的是listView 所以我们就要获取真正的listView然后addHeadView
        lv.addHeaderView(status_detail_info); //要添加的部分 ，操作栏和和正文
        lv.addHeaderView(status_detail_tab);

        //下拉刷新监听
        plv_status_detail.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadComments(1) ;
            }
        });
        //上拉监听当滑动至底部的时候
        plv_status_detail.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                loadComments(curPage+1) ;
            }
        });

        //滚动监听,判断当标题栏滑动到顶部的时候浮动
        plv_status_detail.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //当前的可见Item大于等于2的时候，可见，0是下拉刷新的headView，1是微博信息，2 是浮动的操作栏
                shadow_status_detail_tab.setVisibility(
                        firstVisibleItem >= 2 ? View.VISIBLE : View.GONE); // firstVisibleItem--当前第一个课件的Item

            }
        });
    }

    private void initBottomBar() {
        //底部的互动栏包括，转发、评论、点赞
        ll_bottom_control = (LinearLayout) findViewById(R.id.status_detail_controlbar) ;
        ll_share_bottom = (LinearLayout) ll_bottom_control.findViewById(R.id.ll_share_bottom) ;
        tv_share_bottom = (TextView) ll_bottom_control.findViewById(R.id.tv_share_bottom) ;
        ll_comment_bottom = (LinearLayout) ll_bottom_control.findViewById(R.id.ll_comment_bottom) ;
        tv_comment_bottom = (TextView) ll_bottom_control.findViewById(R.id.tv_comment_bottom) ;
        ll_like_bottom = (LinearLayout) ll_bottom_control.findViewById(R.id.ll_like_bottom) ;
        tv_like_bottom = (TextView) ll_bottom_control.findViewById(R.id.tv_like_bottom) ;

        ll_bottom_control.setBackgroundResource(R.color.white);
        ll_share_bottom.setOnClickListener(this);
        ll_comment_bottom.setOnClickListener(this);
        ll_like_bottom.setOnClickListener(this);
    }

    private void setData() {
        // listView headerView - 微博信息
        User user = statuses.getUser();
        imageLoader.displayImage(user.getProfile_image_url(), iv_avatar,
                ImageOptHelper.getAvatarOptions());
        tv_subhead.setText(user.getName());
        tv_caption.setText(DateUtils.getShortTime(statuses.getCreated_at()) +
                "  来自" + Html.fromHtml(statuses.getSource()));

        setImages(statuses, include_status_image, gv_img, iv_img);

        if (TextUtils.isEmpty(statuses.getText())) {
            tv_content.setVisibility(View.GONE);
        } else {
            tv_content.setVisibility(View.VISIBLE);
            SpannableString weiboContent = StringUtils.getWeiboContent(
                    this, tv_content, statuses.getText());
            tv_content.setText(weiboContent);
        }

        Statuses retweetedStatus = statuses.getRetweeted_status();
        if (retweetedStatus != null) {
            include_status_retweeted.setVisibility(View.VISIBLE);
            String retweetContent = "@" + retweetedStatus.getUser().getName()
                    + ":" + retweetedStatus.getText();
            SpannableString weiboContent = StringUtils.getWeiboContent(
                    this, tv_retweeted_content, retweetContent);
            tv_retweeted_content.setText(weiboContent);
            setImages(retweetedStatus, include_status_retweeted_image,
                    gv_retweeted_img, iv_retweeted_img);
        } else {
            include_status_retweeted.setVisibility(View.GONE);
        }

        // shadow_tab - 顶部悬浮的菜单栏
        shadow_rb_retweets.setText("转发 " + statuses.getReposts_count());
        shadow_rb_comments.setText("评论 " + statuses.getComments_count());
        shadow_rb_likes.setText("赞 " + statuses.getAttitudes_count());
        // listView headerView - 添加至列表中作为header的菜单栏
        rb_retweets.setText("转发 " + statuses.getReposts_count());
        rb_comments.setText("评论 " + statuses.getComments_count());
        rb_likes.setText("赞 " + statuses.getAttitudes_count());

        // bottom_control - 底部互动栏,包括转发/评论/点赞
        tv_share_bottom.setText(statuses.getReposts_count() == 0 ?
                "转发" : statuses.getReposts_count() + "");
        tv_comment_bottom.setText(statuses.getComments_count() == 0 ?
                "评论" : statuses.getComments_count() + "");
        tv_like_bottom.setText(statuses.getAttitudes_count() == 0 ?
                "赞" : statuses.getAttitudes_count() + "");
    }

    private void setImages(final Statuses status, ViewGroup vgContainer, GridView gvImgs, final ImageView ivImg) {
        if (status == null) {
            return;
        }

        ArrayList<PicUrls> picUrls = status.getPic_urls();
        String picUrl = status.getBmiddle_pic();

        if ( picUrls.size() != 0 ) {
            vgContainer.setVisibility(View.VISIBLE);
            if ( picUrls.size() > 1 ) { //多图
                gvImgs.setVisibility(View.VISIBLE);
                ivImg.setVisibility(View.GONE);

                StatusGridImgsAdapter gvAdapter = new StatusGridImgsAdapter(this,picUrls) ;
                gvImgs.setAdapter(gvAdapter);
                gvImgs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(StatusDetailActivity.this, ImageBrowserActivity.class) ;
                        intent.putExtra("status" ,status) ;
                        intent.putExtra("position" ,position) ;
                        startActivity(intent) ;
                    }
                });
            }else { //单图
                gvImgs.setVisibility(View.GONE);
                ivImg.setVisibility(View.VISIBLE);

                Log.d(TAG,"wangkq--> setImages  position: "+"StatusDe :"+"  pic_url: " +picUrl) ;
                imageLoader.displayImage(picUrl, ivImg);
                //点击单图事件
                ivImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(StatusDetailActivity.this, ImageBrowserActivity.class) ;
                        intent.putExtra("status" ,status) ;
                        startActivity(intent) ;
                    }
                });
            }
        }else{
            vgContainer.setVisibility(View.GONE);
        }

    }

    /* @param id         需要查询的微博ID。
    * @param since_id   若指定此参数，则返回ID比since_id大的评论（即比since_id时间晚的评论），默认为0。
    * @param max_id     若指定此参数，则返回ID小于或等于max_id的评论，默认为0。
    * @param count      单页返回的记录条数，默认为50
    * @param page       返回结果的页码，默认为1。
    * @param authorType 作者筛选类型，0：全部、1：我关注的人、2：陌生人 ,默认为0。可为以下几种 :
    *                   <li>{@link #AUTHOR_FILTER_ALL}
    *                   <li>{@link #AUTHOR_FILTER_ATTENTIONS}
    *                   <li>{@link #AUTHOR_FILTER_STRANGER}
    * @param listener   异步请求回调接口
    */

    private void loadComments(final int page) {


        // 获取当前已保存过的 Token
        mAccessToken = AccessTokenKeeper.readAccessToken(this);

        mCommentsAPI = new CommentsAPI(this, Constants.APP_KEY, mAccessToken);

        mCommentsAPI.show(statuses.getId(), 0, 0, 20, page, 0, new RequestListener() {
            @Override
            public void onComplete(String response) {
                //如果是第一页，先清空数据
                if (page == 1) {
                    comments.clear();
                }

                curPage = page ; //把加载页赋值给当前页

                // 解析返回数据
                Gson gson = new Gson();
                CommentsShow commentsShow = gson.fromJson(response, CommentsShow.class);

                // 更新评论信息数,包括正常评论栏，隐藏的评论栏，底部的操作栏
                tv_comment_bottom.setText(commentsShow.getTotal_number() == 0 ?
                        "评论" : commentsShow.getTotal_number() + "");
                shadow_rb_comments.setText("评论 " + commentsShow.getTotal_number());
                rb_comments.setText("评论 " + commentsShow.getTotal_number());

                //将获取到的评论信息添加到列表上
                addData(commentsShow) ;

                // 判断是否需要滚动至评论部分
                if(scroll2Comment) {
                    plv_status_detail.getRefreshableView().setSelection(2); //定位在评论位置，此时为2
                    scroll2Comment = false ; //再把标识位设为false
                }

            }

            @Override
            public void onWeiboException(WeiboException e) {

            }
        });
    }

    //添加数据
    private void addData(CommentsShow commentsShow) {
        for(Comment comment : commentsShow.getComments()){
            //接口 List<E>containsboolean contains(Object o)如果列表包含指定的元素，则返回 true。
            // 更确切地讲，当且仅当列表包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时才返回 true。

            Log.d(TAG ,"comment--?"+"befor") ;
            if( !comments.contains(comment) ){ //list.contains(Bean) ,防止数据的重复添加
                Log.d(TAG ,"comment--?"+"inting") ;
                comments.add(comment) ; //数据添加到集合中
            }
            Log.d(TAG ,"comment--?"+"after") ;
        }
        // 添加完后,通知ListView刷新页面数据
        adapter.notifyDataSetChanged();
        plv_status_detail.onRefreshComplete();

        // 用条数判断,当前评论数是否达到总评论数,未达到则添加更多加载footView,反之移除
        if( comments.size() < commentsShow.getTotal_number() ){
            addFootView( plv_status_detail, footView ) ;
        }else {

            removeFootView( plv_status_detail, footView ) ;
        }
    }

    //添加footView
    private void addFootView( PullToRefreshListView plvHome, View footView ) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() == 1) {
            lv.addFooterView(footView);
        }
    }

    //移除footView
    private void removeFootView( PullToRefreshListView plvHome, View footView ) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() > 1) {
            lv.removeFooterView(footView);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 如果Back键返回,取消发评论等情况,则直接return,不做后续处理
        if(resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) { //根据返回的数据判断
            case REQUEST_CODE_WRITE_COMMENT :

                //如果评论发送成功的返回结果，则重新加载最新评论，同时要求滚动至评论部分
                boolean sendCommentSuccess = data.getBooleanExtra("sendCommentSuccess" ,false) ;
                if(sendCommentSuccess){
                    scroll2Comment = true ;
                    loadComments(1) ;
                }
                break;
            default:
                break;
        }
    }
}
